package org.example.course.common.utils;

import org.example.course.domain.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Classname WebUtils
 * @Description TODO
 * @Date 2020/2/8 16:05
 * @Created by
 */
public class WebUtils {
    /**
     * 得到requset
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        return request;
    }

    /**
     * 得到session
     *
     * @return
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * 得到session里面的用户
     *
     * @return
     */
    public static User getSessionUser() {
        User user = (User) getSession().getAttribute("user");
        return user;
    }

    /**
     * 得到session里面的用户名
     *
     * @return
     */
    public static String getSessionUserName() {
        User user = (User) getSession().getAttribute("user");
        return user.getName();
    }

    /**
     * 设置用户到session
     */
    public static void setSessionUser(User user) {
        getSession().setAttribute("user", user);
    }

}
